import os
import sys
from Node import Package, Module


class PackageManager(object):
    def __init__(self, root):
        self.root = root

    def build_skeleton(self, root = None):
        self.apply_on_tree(self.root, self._create_node)
    

    def apply_on_tree(self, tree, func):
        for node in tree:
            func(node)
            self.apply_on_tree(node, func)

    def _create_node(self, node):
        if isinstance(node, Package):
            if not os.path.exists(node.get_path()):
                print "Creating directory %s" % node.get_path()
                os.mkdir(node.get_path())
        elif isinstance(node, Module):
            if not os.path.exists(node.get_path()):
                print "Creating file %s" % node.get_path()
                fd = file(node.get_path(),"w")
                fd.close()
                
            
    def create_init_file(self):
        init_fd = file(os.path.join(self.root.get_path(),"init.el"),"w")
        print >> init_fd, "(setq ROOT-PATH \"%s\")" % self.root.get_path()
        def f(node):
            if isinstance(node, Package):
                print >> init_fd, "(setq load-path (append load-path (list \"%s\")))" % node.get_path()
            elif isinstance(node, Module):
                print >> init_fd, "(load-file \"%s\")" % node.get_path()
        self.apply_on_tree(self.root, f)
        init_fd.close()

    def init(self):
        self.build_skeleton()
        self.create_init_file()

    
        
        
COMMANDS = {"build_skeleton":None,
            "create_init_file":None,
            "init":None
            }

def usage():
    print "Usage: %s <command>" % sys.argv[0]
    print "commands:"
    for command in COMMANDS:
        print "\t%s" % command
    exit(1)
    
if __name__ == "__main__":
    if len(sys.argv) < 2 or sys.argv[1] not in COMMANDS:
        usage()
    from Configuration import GLOBAL_PACKAGE
    pm = PackageManager(GLOBAL_PACKAGE)
    getattr(pm, sys.argv[1])()
            

    
    
